/* Copyright 2012 Ali H. Caliskan.  All rights reserved.

   This file is part of Sysmkr.

   Sysmkr is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package main

import (
	"fmt"
	"libmkr"
	"os"
	"path/filepath"
)

func InsertDataBase(name string, vers string, grp string, url string, path string, sys string) {

	libmkr.InsertDataBaseEntrySrc(libmkr.RecipeSQLiteExt, name, vers, grp, url, path, sys)
}


func UpdateDataBase(name string, SysFile string) {

	_, err := os.Stat(SysFile)

	if err == nil {
		sys := libmkr.ReadFile(SysFile)

		fmt.Println("info: updating system:", name)

		libmkr.UpdateSysSrc(libmkr.RecipeSQLiteExt, name, sys)

		fmt.Println("      done")
	}

	os.Exit(0)
}


func main() {

	name := libmkr.GetArg(0)
	vers := libmkr.GetArg(1)
	grp := libmkr.GetArg(2)
	url := libmkr.GetArg(3)
	path := libmkr.GetArg(4)
	sys := ""

	RcsFile := filepath.Join(name, name + libmkr.RcsFileExt)
	SysFile := filepath.Join(name, name + libmkr.SysFileExt)

	_flag := libmkr.GetArg(0)
	_name := libmkr.GetArg(1)

	if _flag == "update" {
		if len(_name) == 0  {
			fmt.Println("warning: missing flag")
			return
		}

		SysFile := filepath.Join(_name, _name + libmkr.SysFileExt)

		UpdateDataBase(_name, SysFile)
	}

	if len(name) == 0 || len(vers) == 0 || len(grp) == 0 || len(url) == 0 {
		fmt.Println("warning: missing flag")
		return
	}

	_, err := os.Stat(RcsFile)

	if err != nil {
		os.Mkdir(name, 0755)
		args := []string{"/usr/share/sysmkr/proto.recipe", RcsFile}
		libmkr.Run("cp", args...)
	}

	if path == "" {
		path = "%name-%vers"
	}

	fmt.Println("info: new database entry:", name)

	_, err = os.Stat(SysFile)

	if err == nil {
		sys := libmkr.ReadFile(SysFile)

		InsertDataBase(name, vers, grp, url, path, sys)

	} else {

		InsertDataBase(name, vers, grp, url, path, sys)
	}

	fmt.Println("      done")
}

